//
//  YunDanHuiDanShangJiaoVC.m
//  ReceiptDelivery
//
//  Created by 吕晶 on 2020/10/12.
//  Copyright © 2020 吕晶. All rights reserved.
//

#import "YunDanHuiDanShangJiaoVC.h"
#import "YunDanHuiDanShangJiaoModel.h"
#import "YunDanHuiDanShangJiaoCell.h"
#import "BRDatePickerView.h"

@interface YunDanHuiDanShangJiaoVC ()<UITableViewDelegate,UITableViewDataSource,TZImagePickerControllerDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) YunDanHuiDanShangJiaoModel *model;

@end

@implementation YunDanHuiDanShangJiaoVC

-(YunDanHuiDanShangJiaoModel *)model {
    if (!_model) {
        _model = [YunDanHuiDanShangJiaoModel new];
    }
    return _model;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH - NaviHeight - BottomHeight)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = Color_backgroundColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"回单上缴";
    [self.view addSubview:self.tableView];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YunDanHuiDanShangJiaoCell *cell = [YunDanHuiDanShangJiaoCell YunDanHuiDanShangJiaoCellWithTableView:tableView];
    cell.model = self.model;
    __weak_self;
    cell.timeBlock = ^{
        [BRDatePickerView showDatePickerWithTitle:@"上缴日期" dateType:UIDatePickerModeDateAndTime defaultSelValue:nil minDateStr:nil maxDateStr:nil isAutoSelect:YES resultBlock:^(NSString *selectValue) {
            weakself.model.time = selectValue;
            [tableView reloadData];
        }];
    };
    cell.addBlock = ^{
        [weakself chooseImg];
    };
    cell.deleteBlock = ^(NSInteger idx) {
        NSMutableArray *arr = [NSMutableArray arrayWithArray:weakself.model.imgList];
        [arr removeObjectAtIndex:idx];
        weakself.model.imgList = arr;
        [tableView reloadData];
    };
    cell.sureBlock = ^{
        if (!weakself.model.time.length) {
            [MBProgressHUD leShowFailedHUD:weakself.view message:@"请先选择时间"];
            return;
        }
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确定上缴？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakself requestForQianShou];
        }];
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:sureAction];
        [alert addAction:cancleAction];
        [self presentViewController:alert animated:YES completion:nil];
    };
    return cell;
}

- (void)requestForQianShou {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:self.wa_id forKey:@"wa_id"];
    [dic setObject:self.model.time forKey:@"time"];
    NSMutableString *sign_img = [NSMutableString string];
    [self.model.imgList enumerateObjectsUsingBlock:^(YunDanHuiDanShangJiaoImgModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [sign_img appendFormat:@"%@,",obj.filepath];
    }];
    if (sign_img.length) {
        [sign_img deleteCharactersInRange:NSMakeRange(sign_img.length - 1, 1)];
    }
    [dic setObject:sign_img.length ? sign_img : @"" forKey:@"img"];
    [HttpRequest PostWithApi:ReceiptDeliveryMyShipmentHuiDanShangJiao params:dic progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            [[NSNotificationCenter defaultCenter] postNotificationName:ReceiptDeliveryRefreshWoFaYunList object:nil];
            __weak_self;
            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"已上缴" delayOperation:^{
                [weakself.rt_navigationController popToViewController:weakself.rt_navigationController.rt_viewControllers[1] animated:YES complete:nil];
            }];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

- (void)chooseImg {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:1 delegate:self pushPhotoPickerVc:YES];
        imagePickerVc.isSelectOriginalPhoto = YES;
        imagePickerVc.allowTakeVideo = NO;   // 在内部显示拍视频按
        imagePickerVc.iconThemeColor = [UIColor colorWithRed:31 / 255.0 green:185 / 255.0 blue:34 / 255.0 alpha:1.0];
        imagePickerVc.showPhotoCannotSelectLayer = YES;
        imagePickerVc.cannotSelectLayerColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
        [imagePickerVc setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
            [doneButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        }];
        // 你可以通过block或者代理，来得到用户选择的照片.
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            //通过asset获取原图，方法会先返回缩略图，再返回原图
            [[TZImageManager manager] getOriginalPhotoDataWithAsset:assets.firstObject progressHandler:^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
                
            } completion:^(NSData *data, NSDictionary *info, BOOL isDegraded) {
                [self requestForUpload:data];
            }];
        }];
        [self presentViewController:imagePickerVc animated:YES completion:nil];
}

- (void)requestForUpload:(NSData *)image {
    [MBProgressHUD leShowHUDWithMessage:@"上传中" activity:YES];
    [HttpRequest postImgDataWithUrl:ReceiptDeliveryWoFaYunHuiDanUploadImg imgData:image imgFile:@"file" withParameter:@{@"type":@"1"} sucess:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            YunDanHuiDanShangJiaoImgModel *model = [YunDanHuiDanShangJiaoImgModel new];
            model.url = [responseObject objectForKey:@"url"];
            model.filepath = [responseObject objectForKey:@"filepath"];
            NSMutableArray *mut = [NSMutableArray arrayWithArray:self.model.imgList];
            [mut addObject:model];
            self.model.imgList = mut;
            [self.tableView reloadData];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    YunDanHuiDanShangJiaoCell *cell = [YunDanHuiDanShangJiaoCell YunDanHuiDanShangJiaoCellWithTableView:tableView];
    cell.model = self.model;
    return cell.height;
}

@end
